<?php

namespace app\api\controller;

use think\Db;
use think\Request;
use think\Log;
use think\Cache;
use GatewayClient\Gateway;
use Qcloud\Cos\Client;
use app\api\model\Privatechat;

class Articlecheck extends Common
{
    public function vidoenotify()
    {
        // Log::write('测试回调','error');
        $params = input();
        $taskid = $params['TaskId'];
        $suggestion = $params['Suggestion'];
        $labels = $params['Labels'];
        $label = $params['Label'];
        $labelscore = 0;
        if(sizeof($labels)){
            $labelscore = $labels[0]['Score'];
        }else{
            // return;
        }

        // if($suggestion == 'Pass'){
        if($suggestion == 'Block'){
            $audioText = $params['AudioText'];
            $imagesegments = $params['ImageSegments'][0]['Result']['Url'];

            $userid_real = $userid = trtcuser($imagesegments);
            $userinfo = _user($userid);
            if ($userinfo && $userinfo['reg'] == 2 && $userinfo['authcode']) {
                $userid_real = $userinfo['authcode'];
            }

            $lianmai = Cache::store('redis')->get('lianmaiuser:'.$userid_real);
            if ($lianmai) {
                $chat = Db::name('privatechat')->where(['order_id'=>$lianmai])->find();
                if ($chat && strlen($chat['data']) < 1900) {
                    $chatData = json_decode($chat['data'], true);
                    if (!isset($chatData['hpr'])) {
                        $chatData['hpr'] = $userid.'触发鉴黄警报';
                        Db::name('privatechat')->where(['id'=>$chat['id']])->update(['data'=>json_encode($chatData, JSON_UNESCAPED_UNICODE)]);
                    }
                }
            }

            $msg = '请注意聊天规范，否则系统将对账号封禁';
            $msg = '系统中断';

            if (false) {
                $order_id = Db::name('shenhe_task')->where(['task_id'=>$taskid])->value('order_id');
                $order = Db::name('order_common')->find($order_id??0);
                if ($order) {
                    $nums = [
                        [
                            ['num'=>10,'hour'=>24],
                            ['num'=>7,'hour'=>12],
                            ['num'=>5,'hour'=>7],
                            ['num'=>3,'hour'=>3],
                            ['num'=>1,'hour'=>1],
                        ],
                        [
                            ['num'=>10,'hour'=>3],
                            ['num'=>7,'hour'=>2],
                            ['num'=>5,'hour'=>1.5],
                            ['num'=>3,'hour'=>1],
                            ['num'=>1,'hour'=>0.5],
                        ]
                    ];

                    $count = Db::name('shenhe_task_records')->where(['userid'=>$userid, 'create_time'=>['>',strtotime('2024-01-15 15:59:00')]])->group('taskid')->count();
                    $count++;
                    $key = $order['user_id'] == $userid ? 1 : 0;

                    $options = $nums[$key];
                    foreach ($options as $k => $v) {
                        if ($count >= $v['num']) {
                            $banned_time = $v['hour'] < 1 ? ($v['hour'] * 60) . '分钟': $v['hour'] . '小时';
                            $msg = '你因视频中涉黄被封号'.$banned_time.',请勿涉黄';

                            $banned_end_time = date('Y-m-d H:i:s', strtotime('+'.($v['hour'] * 60).' minutes'));
                            Db::name('user')->where(['id'=>$userid])->update(['is_banned'=>1,'banned_end_time'=>$banned_end_time,'banned_desc'=>$msg]);
                            Db::name('config_personal')->where(['user_id'=>$userid])->update(['is_read_rule'=>0]);
                            $adminLog = [
                                'channel' => 3,
                                'toward' => 0,
                                'money' => 0,
                                'admin' => '',
                                'user_id' => $userid,
                                'content' => '封禁账号至' . $banned_end_time . ' 原因：' . $msg
                            ];
                            Db::name('admin_logs')->insert($adminLog);
                            // Privatechat::notice($userid, '封禁账号至' . $banned_end_time . ' 原因：'.$msg, json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE), 1, -3);
                            break;
                        }
                    }
                }
            } else {
                // $bannedVideoState = $this->bannedVideo($userid_real);
                // if ($bannedVideoState) {
                //     $msg = $bannedVideoState;
                // }
            }

            $message = json_encode(['code' => 200, 'action' => 'SystemWarningAndExit', 'msg' => $msg]);
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid_real, $message);

            Db::name('shenhe_task_records')->insert([
                'taskid'        =>  $taskid,
                'userid'        =>  $userid,
                'suggestion'    =>  $suggestion,
                'label'         =>  $label,
                'score'         =>  $labelscore,
                'audiotext'     =>  $audioText,
                'imagesegments' =>  $imagesegments,
                'create_time'   =>  time()
            ]);

            // 删除文件
            try {
                $filePath = explode('trtc', explode('?', $imagesegments)[0])[1];
                $this->deleteFile($filePath);
            } catch (\Exception $e) {
                Log::write('涉黄文件删除失败'.$imagesegments,'error');
            }
            // return $this->pass($key);
        }

    }


    public function deleteFile($path = '')
    {
        // 替换成你的腾讯云 COS 配置信息
        $secretId = getenv('SECRET_ID');
        $secretKey = getenv('SECRET_KEY');
        $region = 'ap-guangzhou'; // 例如：ap-guangzhou
        $bucket = 'tianyu-content-moderation-1254335172';

        // 创建 COS 客户端
        $client = new Client([
            'region' => $region,
            'credentials' => [
                'secretId' => $secretId,
                'secretKey' => $secretKey,
            ],
        ]);

        // 要删除的文件在 COS 中的路径
        $objectKey = 'segment-/trtc'.$path;

        // 删除文件
        $result = $client->deleteObject([
            'Bucket' => $bucket,
            'Key' => $objectKey,
        ]);

        return $result;
    }

    public function bannedVideo($user_id)
    {
        $userinfo = _user($user_id);
        if (strtotime($userinfo['register_datetime']) < strtotime('2014-01-21 00:00:00')) {
            return false;
        }

        $date = date('Y-m-d');
        $today = Db::name('privatechat_lianmai_video_banned')
                    ->master()
                    ->where(['user_id'=>$user_id, 'date'=>$date])
                    ->find();

        $msg = false;
        if ($today) {
            $expire_time = $banned_time = 0;
            if (($today['num'] + 1) % 5 == 0) {
                $banned_time = time();
                $expire_time = $banned_time + 3600;
                $msg = '账号因涉黄被禁止视频通话至' . date('Y-m-d H:i:s', $expire_time);
                $adminLog = [
                    'channel' => 3,
                    'toward' => 0,
                    'money' => 0,
                    'admin' => '',
                    'user_id' => $user_id,
                    'content' => $msg
                ];
                Db::name('admin_logs')->insert($adminLog);
                Privatechat::notice($user_id, $msg);
            }
            Db::name('privatechat_lianmai_video_banned')
                ->where(['id'=>$today['id']])
                ->update([
                    'num'   =>  Db::raw('num+1'),
                    'banned_time'=>$banned_time,
                    'expire_time'=>$expire_time,
                ]);
        } else {
            Db::name('privatechat_lianmai_video_banned')->insert([
                'user_id'=>$user_id,
                'date'=>$date,
                'num'=>1
            ]);
        }
        return $msg;
    }



}